package com.juben.svr.demos.web;

import com.itextpdf.io.util.StreamUtil;
import com.juben.svr.domain.*;
import com.juben.svr.domain.Enum.EmailType;
import com.juben.svr.service.EmailValidationService;
import com.juben.svr.service.UserService;
import com.juben.svr.service.impl.TimeService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
//import org.springframework.security.access.prepost.PreAuthorize;
//import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import com.juben.svr.service.TokenService;
import com.juben.svr.service.TokenService;

import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import javax.xml.transform.Result;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:5173",allowedHeaders = "*",allowCredentials = "true")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private EmailValidationService emailValidationService;
    @Autowired
    private TimeService timeService;

    Email_validation email_validation = new Email_validation();


//    @Value("${jwt.secret}")
    private String SECRET_KEY = "your_secret_key";


    //获取用户信息接口
    @RequestMapping(value = "/getuser")
    //用户身份鉴权
    public ResponseEntity<ResponseMessage> getUserInfo(@RequestHeader("Authorization") String token) {
        System.out.println("/getUser");
        // 从 Authorization 头中提取 JWT 令牌
        System.out.println("token:"+token);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 删除 "Bearer " 前缀
            System.out.println("删除前缀后："+token);
        } else {
            return ResponseEntity.status(200).body(new ResponseMessage(401, "无效的令牌", null, null));
        }

        try {
             // 验证令牌并解析用户 ID
            System.out.println("开始解析用户id");
            Integer userId = tokenService.getUserIdFromToken(token);
            System.out.println("userId:"+userId);

            // 根据用户 ID 获取用户信息
            System.out.println("userId:"+userId);
            User userInfo = userService.getUserById(userId); // 或者根据您的 DAO 方法进行调整
            System.out.println("userInfo:"+userInfo);
            if (userInfo != null) {
                return ResponseEntity.ok(new ResponseMessage(200, "获取用户信息成功", null, userInfo));
            } else {
                return ResponseEntity.status(200).body(new ResponseMessage(404, "用户未找到", null, null));
            }
        } catch (Exception e) {
            System.out.println("验证失败：" + e.getMessage());
            return ResponseEntity.status(401).body(new ResponseMessage(401, "验证失败，令牌无效或已过期", null, null));
        }
    }
    //通过id获取用户信息
    @PostMapping("/getUserById/{uid}")
    public ResponseEntity<ApiResponse> getUserById(@PathVariable Integer uid,@RequestHeader ("Authorization") String token) {
        System.out.println("/getUserById");
        System.out.println("前端传来的id:"+uid);
        System.out.println("前端传过来的用户token:"+token);
        //用户身份鉴权
        // 从 Authorization 头中提取 JWT 令牌
        System.out.println("token:"+token);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 删除 "Bearer " 前缀
        } else {
            return ResponseEntity.status(200).body(new ApiResponse(401, "无效的令牌" , token));
        }
        // 验证令牌
        try {
            // 验证令牌并解析用户 ID
            System.out.println("开始解析用户id");
            Integer userId = tokenService.getUserIdFromToken(token);
            System.out.println("userId:"+userId);
            System.out.println("令牌验证成功");
            User userInfo = userService.getUserById(uid);
            if (userInfo != null) {
                return ResponseEntity.ok(new ApiResponse(200, "获取用户信息成功", userInfo));
            } else {
                return ResponseEntity.status(200).body(new ApiResponse(404, "用户未找到", null));
            }
        }catch (Exception e){
            return ResponseEntity.status(200).body(new ApiResponse(401, "令牌验证失败" , token));
        }

    }


    //修改用户接口
    @PostMapping("/updateuser")
    public ResponseEntity<ResponseMessage> updateUser(@RequestBody User user,@RequestHeader ("Authorization") String token) {
        System.out.println("/updateuser");
        System.out.println("前端传来的user:"+user);
        System.out.println("前端传过来的用户信息:"+user);
        //用户身份鉴权
        // 从 Authorization 头中提取 JWT 令牌
        System.out.println("token:"+token);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 删除 "Bearer " 前缀
        } else {
            return ResponseEntity.status(401).body(new ResponseMessage(401, "无效的令牌", null, null));
        }
        //获取用户id
        try {
            // 验证令牌并解析用户 ID
            System.out.println("开始解析用户id");
            Integer userId = tokenService.getUserIdFromToken(token);
            System.out.println("userId:"+userId);
            user.setUID(userId);
            Boolean result = userService.updateUserInfo(user);
            System.out.println("result:"+result);
            if (result) {
                return ResponseEntity.ok(new ResponseMessage(200, "更新用户信息成功", null, null));
            } else {
                return ResponseEntity.status(500).body(new ResponseMessage(500, "更新用户信息失败", null, null));
            }
        }catch (Exception e){
            return ResponseEntity.status(500).body(new ResponseMessage(500, "更新用户信息失败", null, null));
        }
    }

    //获取用户角色列表接口
    @GetMapping("/getUserRoleList")
    public List<role> getUserRoleList() {
        System.out.println("/getUserRoleList");
        List<role> roleList = userService.getRoleList();
        return roleList;
    }

    // 发送验证码接口
    @GetMapping("/sendRegisterEmail/{email}")
    public ResponseEntity<ApiResponse> sendRegisterEmail(@PathVariable String email) {
        System.out.println("/注册邮箱验证: " + email);

        if (email == null || email.isEmpty()) {
            return ResponseEntity.status(400).body(new ApiResponse(400, "邮箱为空", null));
        }
        //将邮箱和对应的验证码类型封装到Email_validation对象中
        email_validation.setEmail(email);
        email_validation.setEmailType(EmailType.注册邮箱验证);

        // 获取验证信息
//        Email_validation emailValidation = emailValidationService.getEmailValidation(email);
//
        Email_validation emailValidation = emailValidationService.getEmailValidation(email_validation);
        System.out.println("验证信息：" + emailValidation);
        if (emailValidation == null) {
            // 这里可以处理未找到验证时间的情况，比如直接返回错误，或者发送验证码。
            userService.RegisterEmail(email);
            return ResponseEntity.status(200).body(new ApiResponse(200, "发送成功", null));
        }
        // 定义日期格式常量
        final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); // 请确保格式与实际格式匹配
        try {
            Date validationTime = format.parse(emailValidation.getTime()); // 将字符串转换为 Date
            Date now = new Date();

            // 检查验证码是否过期
            System.out.println("验证码过期时间：" + validationTime);
            System.out.println("当前时间：" + now);
            if (!validationTime.before(now)) {
                return ResponseEntity.status(200).body(new ApiResponse(400, "验证码未过期", null));
            }

            // 验证码过期，重新注册邮箱并发送验证码
            userService.RegisterEmail(email);
            return ResponseEntity.status(200).body(new ApiResponse(200, "发送成功", null));

        } catch (ParseException e) {
            // 处理解析异常
            e.printStackTrace();
            return ResponseEntity.status(500).body(new ApiResponse(500, "时间格式错误", null));
        }
    }

    //用户注册接口
    @PostMapping("/register")
    public ResponseEntity<ApiResponse> register(@RequestBody User user) {
        System.out.println("/register");
        System.out.println("前端传来的user:"+user);
        System.out.println(user.getUpassword());
        String email = user.getEmail();
        String emailCode = user.getEmailCode();
        String uaccount = user.getAccount();

        email_validation.setEmail(email);
        email_validation.setEmailType(EmailType.注册邮箱验证);

        //校验验证码
        Email_validation emailValidation = emailValidationService.getEmailValidation(email_validation);
        System.out.println("验证信息：" + emailValidation);
        // 定义日期格式常量
        final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); // 请确保格式与实际格式匹配
        try {
            Date validationTime = format.parse(emailValidation.getTime()); // 将字符串转换为 Date
            Date now = new Date();

            // 检查验证码是否过期
            System.out.println("验证码过期时间：" + validationTime);
            System.out.println("当前时间：" + now);
            if (!validationTime.before(now)) {
                System.err.println("验证码未过期");
                //校验验证码
                if(emailCode.equals(emailValidation.getCode())){
                    System.out.println("验证码正确");
                    //判断账号是否已存在
                    if ( userService.getUserByAccount(uaccount) != null) {

                        System.out.println("账号已存在："+userService.getUserByAccount(uaccount));
                        return ResponseEntity.status(200).body(new ApiResponse(400, "账号已存在", null));
                    }

                    //验证码正确后删除此验证码
                    email_validation.setEmail(email);
                    email_validation.setEmailType(EmailType.注册邮箱验证);
                    boolean deleteresult = emailValidationService.deleteEmailValidation(email_validation);
                    System.out.println("删除结果：" + deleteresult);
                    //注册用户

                    user.setUdate(timeService.getCurrentDateTime());
                    System.out.println("开始注册user:"+user);
                    Boolean result = userService.addUser(user);
                    System.out.println("result:"+result);
                    if (result) {

                        return ResponseEntity.ok(new ApiResponse(200, "注册成功", null));
                    } else {
                        return ResponseEntity.status(200).body(new ApiResponse(500, "注册失败", null));
                   }
                }else {
                    System.err.println("验证码错误");
                    return ResponseEntity.status(200).body(new ApiResponse(400, "验证码错误", null));
                }

            }else {
                //验证码正确后删除此验证码
                email_validation.setEmail(email);
                email_validation.setEmailType(EmailType.注册邮箱验证);
                boolean deleteresult2 = emailValidationService.deleteEmailValidation(email_validation);
                System.out.println("删除结果：" + deleteresult2);
                System.err.println("验证码已过期");
                return ResponseEntity.status(200).body(new ApiResponse(400, "验证码已过期", null));
            }
        } catch (ParseException e) {
            // 处理解析异常
            e.printStackTrace();
            return ResponseEntity.status(500).body(new ApiResponse(500, "时间格式错误", null));
        }


    }

    //普通修改密码
    @PostMapping("/changepassword")
    public ResponseEntity<ResponseMessage> changePassword(@RequestBody ChangePassWordRequest request,@RequestHeader ("Authorization") String token) {
        System.out.println("/changepassword");
        System.out.println("前端传来的request:"+request);
        //用户身份鉴权
        // 从 Authorization 头中提取 JWT 令牌
        System.out.println("token:"+token);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 删除 "Bearer " 前缀
        } else {
            return ResponseEntity.status(401).body(new ResponseMessage(401, "无效的令牌", null, null));
        }
        //获取用户id
        try {
            // 验证令牌并解析用户 ID
            System.out.println("开始解析用户id");
            Integer userId = tokenService.getUserIdFromToken(token);
            System.out.println("userId:"+userId);
            //密码验证
            User user = userService.getUserById(userId);
            if (!user.getUpassword().equals(request.getOldPassword())){
                System.out.println("旧密码错误");
                return ResponseEntity.status(200).body(new ResponseMessage(400, "旧密码错误", null, null));
            }
            // 修改密码
            boolean result =userService.changePassword(userId, request);
            System.out.println("修改密码结果:"+result);
            if (result){
                System.out.println("修改成功");
                return ResponseEntity.ok(new ResponseMessage(200, "修改成功", null, null));
            }else {
                System.out.println("修改失败");
                return ResponseEntity.status(200).body(new ResponseMessage(400, "修改失败", null, null));
            }

        }catch (Exception e){
            System.out.println("无效的令牌");
            return ResponseEntity.status(401).body(new ResponseMessage(401, "无效的令牌", null, null));
        }
    }

    //通过邮箱找回密码——发送验证码
    @GetMapping("/forgetpassCode/{email}")
    public ResponseEntity<ResponseMessage> forgetPassword(@PathVariable String email) {
        System.out.println("/forgetpassword");
        System.out.println("email:"+email);
        //发送验证码，不用鉴权，直接发送
       boolean result = emailValidationService.passEmailValidation(email);
       if (result){
           return ResponseEntity.ok(new ResponseMessage(200, "发送成功", null, null));
       }else {
           return ResponseEntity.status(200).body(new ResponseMessage(400, "发送失败", null, null));
       }
    }

    //校验验证码，token后进行密码的修改
    @PostMapping("/forgetpassword")
    public ResponseEntity<ApiResponse> forgetPassword(@RequestBody ChangePassWordRequest request,@RequestHeader ("Authorization") String token) {
        System.out.println("/forgetpassword");
        System.out.println("前端传来的request:"+request);
        String email = request.getEmail();
        System.out.println("token:"+token);
        // 从 Authorization 头中提取 JWT 令牌
        System.out.println("token:"+token);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 删除 "Bearer " 前缀
        } else {
            return ResponseEntity.status(200).body(new ApiResponse(401, "无效的令牌", null));
        }
        // 验证令牌并解析用户 ID
        System.out.println("开始解析用户id");
        Integer userId = tokenService.getUserIdFromToken(token);
        System.out.println("userId:"+userId);
        //从数据库查询验证码
            //从数据库中查询出验证码
            email_validation.setEmail(email);
            email_validation.setEmailType(EmailType.忘记密码邮箱验证);
            Email_validation emailValidation = emailValidationService.getEmailValidation(email_validation);     //emailValidation从数据库中查询的验证码信息
            System.out.println("查询出的验证信息：" + emailValidation);
            // 定义日期格式常量
            final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); // 请确保格式与实际格式匹配
        //校验验证码正确性
        try {
            Date validationTime = format.parse(emailValidation.getTime()); // 将字符串转换为 Date
            Date now = new Date();  // 获取当前时间

            // 检查验证码是否过期
            System.out.println("验证码过期时间：" + validationTime);
            System.out.println("当前时间：" + now);
            if (!validationTime.before(now)) {
                System.err.println("验证码未过期");
                //校验验证码正确性
                String userCode = request.getEmailcode();
                System.out.println("用户输入的验证码：" + userCode);
                System.out.println("数据库中的验证码：" + emailValidation.getCode());
                if(userCode.equals(emailValidation.getCode())){
                    System.out.println("验证码正确");
//                    //判断账号是否已存在
//                    if ( userService.getUserByAccount(uaccount) != null) {
//
//                        System.out.println("账号已存在："+userService.getUserByAccount(uaccount));
//                        return ResponseEntity.status(200).body(new ApiResponse(400, "账号已存在", null));
//                    }
                    //验证码正确后删除此验证码
                    boolean deleteresult = emailValidationService.deleteEmailValidation(email_validation);
                    System.out.println("删除结果：" + deleteresult);

                    //进行密码的修改
                    System.out.println("修改密码");
                    boolean success = userService.changePassword(userId, request);
                    if (success) {
                        System.out.println("密码修改成功");
                        return ResponseEntity.ok(new ApiResponse(200, "密码修改成功", null));
                    } else {
                        System.out.println("密码修改失败");
                        return ResponseEntity.status(200).body(new ApiResponse(400, "密码修改失败", null));
                    }



                }else {
                    System.err.println("验证码错误");
                    return ResponseEntity.status(200).body(new ApiResponse(400, "验证码错误", null));
                }

            }else {
                System.out.println("验证码已过期");
                //验证码已过期，删除此验证码
                boolean deleteresult2 = emailValidationService.deleteEmailValidation(email_validation);
                System.out.println("删除结果：" + deleteresult2);
                System.err.println("验证码已过期");
                return ResponseEntity.status(200).body(new ApiResponse(400, "验证码已过期", null));
            }
        } catch (ParseException e) {
            // 处理解析异常
            e.printStackTrace();
            return ResponseEntity.status(500).body(new ApiResponse(500, "时间格式错误", null));
        }

    }

    @GetMapping("/forgetpassCode")
    public ResponseEntity<ResponseMessage> forgetPassword2(@PathVariable String email) {
        System.out.println("/forgetpassword");
        System.out.println("email:"+email);
        //发送验证码，不用鉴权，直接发送
        boolean result = emailValidationService.passEmailValidation(email);
        if (result){
            return ResponseEntity.ok(new ResponseMessage(200, "发送成功", null, null));
        }else {
            return ResponseEntity.status(200).body(new ResponseMessage(400, "发送失败", null, null));
        }
    }


}
